<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\ImportExportEvent;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\AdminUser;
use App\Models\V1\NewStudent;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
use Auth;


class NewStudentExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入新生数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新生数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }

            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(31);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'enrollment_numbering' => $item[0],
                        'exam_code' => $item[1],
                        'name' => $item[2],
                        'sex' => $item[3],
                        'avatar' => $item[4],
                        'mobile' => $item[5],
                        'address' => $item[6],
                        'card_type' => $item[7],
                        'card_number' => $item[8],
                        'birthday' => $item[9],
                        'original_type' => $item[10],
                        'enrollment_type' => $item[11],
                        'graduated_school' => $item[12],
                        'exam_province' => $item[13],
                        'exam_area' => $item[14],
                        'school_type' => $item[15],
                        'score' => $item[16],
                        'political_status' => $item[17],
                        'enrollment_category' => $item[18],
                        'enrollment_code' => $item[19],
                        'enrollment_directory' => $item[20],
                        'major_directory_code' => $item[21],
                        'academic_category' => $item[22],
                        'read_year' => $item[23],
                        'admission_property' => $item[24],
                        'school_mode' => $item[25],
                        'ethnic' => $item[26],
                        'household' => $item[27],
                        'support_type' => $item[28],
                        'enrollment_teacher' => $item[29],
                        'remark' => $item[30],
                    ];
                    if (!empty($item[1]) && !empty($item[2])) {
                        NewStudent::updateOrCreate(['exam_code'=>$item[1]],$insert_data);
                        $this->registerUser($item[1]);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出新生数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['招生编号', '考试号','姓名', '性别（1:男 2:女）', '照片','联系电话',
            '家庭住址', '证件类型', '证件号','出生日期', '生源类别', '招生类型',
            '毕业学校', '报考省市', '报考区县','学校类别', '成绩', '政治面貌',
            '招生类别', '招生代码','招生目录', '专业目录代码', '学制类别',
            '就读年限', '录取性质','办学模式', '民族', '户口性质',
            '资助类型', '招生老师', '备注'];
        $arrival_code = $this->getArrivalCode();
        if (empty($arrival_code)) {
            $response['rspStatus'] = false;
            $response['rspMsg'] = '请先启动迎新换届';
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
        $custodian = NewStudent::where('arrival_code',$arrival_code)->select('enrollment_numbering', 'exam_code','name',
        'sex','avatar','mobile','address','card_type',
        'card_number','birthday','original_type','enrollment_type','graduated_school',
        'exam_province','exam_area','school_type','score','political_status',
        'enrollment_category','enrollment_code','enrollment_directory',
        'major_directory_code','academic_category','read_year','admission_property',
        'school_mode','ethnic','household','support_type','enrollment_teacher', 'remark')->get();
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->enrollment_numbering, $item->exam_code,
                $item->name, $item->sex, $item->avatar, $item->mobile, $item->address,
                $item->card_type, $item->card_number, $item->birthday, $item->original_type,
                $item->enrollment_type, $item->graduated_school, $item->exam_province, $item->exam_area,
                $item->school_type,$item->score, $item->political_status,
                $item->enrollment_category, $item->enrollment_code, $item->enrollment_directory,
                $item->major_directory_code, $item->academic_category, $item->read_year,
                $item->admission_property, $item->school_mode, $item->ethnic, $item->household,
                $item->support_type, $item->enrollment_teacher, $item->remark,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','新生'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('students', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[新生]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['招生编号', '考试号','姓名', '性别（1:男 2:女）', '照片','联系电话',
            '家庭住址', '证件类型', '证件号','出生日期', '生源类别', '招生类型',
            '毕业学校', '报考省市', '报考区县','学校类别', '成绩', '政治面貌',
            '招生类别', '招生代码','招生目录', '专业目录代码', '学制类别',
            '就读年限', '录取性质','办学模式', '民族', '户口性质',
            '资助类型', '招生老师', '备注'];
        $cellDatas = [$header];
        $cellData1 = ['2010299991','111102863','张三','1','','1301882','','','',''
            ,'','','','','','','','','','','','','','','','','','','','',''];
        array_push($cellDatas, $cellData1);
        Excel::create('新生数据导入模版', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('students', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[新生]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    //向登录的数据库表中添加数据
    private function registerUser($code){
        $insert_data = [
            'code' => $code,
            'password' => bcrypt('123456'),
            'is_staff' => 0,
        ];
        AdminUser::updateOrCreate(['code' => $code], $insert_data);
    }
}
